<?php

namespace App\Admin\Forms\User;

use App\Exceptions\ApiException;
use App\Models\UserAsset;
use App\Services\Base\HelpService;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class FreezeBalanceForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        $amount = floatval($input['amount'] ?? 0);
        $remark = $input['remark'] ?? "";
        $uid = $this->payload["id"];
        $user_asset = UserAsset::getContractAccount($uid);

        if ($amount > 0) {
            if ($user_asset->balance < $amount) {
                return $this
                    ->response()
                    ->error('可用余额必须大于所填金额');
            }
        } else {
            if ($user_asset->freeze_all < abs($amount)) {
                return $this
                    ->response()
                    ->error('冻结余额必须大于所填金额');
            }
        }

        try {
            DB::beginTransaction();
            $op_result = $user_asset->assetChange(
                $uid,
                ASSET_SYMBOL_DEFAULT,
                -$amount,
                $amount > 0 ? ASSET_FREEZE_ALL : ASSET_FREEZE_RELEASE,
                '',
                BALANCE_USABLE
            );

            if (!$op_result) {
                throw new ApiException("冻结金额失败(1)");
            }

            $op_result = $user_asset->assetChange(
                $uid,
                ASSET_SYMBOL_DEFAULT,
                $amount,
                $amount > 0 ? ASSET_FREEZE_ALL : ASSET_FREEZE_RELEASE,
                '',
                BALANCE_FREEZE_ALL
            );

            if (!$op_result) {
                throw new ApiException("冻结金额失败(2)");
            }

            DB::commit();

        } catch (\Exception $e) {
            HelpService::forceLog($e);
            DB::rollBack();
        }


        if ($op_result) {
            return $this
                ->response()
                ->success('执行成功')
                ->refresh();
        } else {
            return $this
                ->response()
                ->error('执行失败');
        }
    }

    /**
     * Build a form here.
     */
    public function form()
    {

        $user_asset = UserAsset::getContractAccount($this->payload['id']);
        $balance = asMoney($user_asset->balance);
        $freeze_all = asMoney($user_asset->freeze_all);
        $this->display('balance', '余额')->value("可用余额:{$balance},冻结余额:{$freeze_all}");
        $this->text('amount', __("金额"))
            ->help("支持正负金额，正数表示冻结，负数表示解冻")
            ->required()->rules("notIn:0");
//        $this->textarea('remark', __("备注"))
//            ->placeholder("系统冻结");

        $this->hidden("id")->value($this->getKey());
    }

    public function default()
    {
        return [
            "amount" => 0
        ];
    }
}
